package cn.parus.auth.service;

import cn.parus.auth.POJO.DTO.OpaInput;
import cn.parus.auth.POJO.DTO.OpaOutput;
import cn.parus.auth.constant.rules;
import com.bisnode.opa.client.OpaClient;
import com.bisnode.opa.client.query.OpaQueryApi;
import com.bisnode.opa.client.query.QueryForDocumentRequest;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author: Axel
 * @Description: TODO
 **/
@Slf4j
@Service
public class OpaClientService {

    @Value("${mini-gateway.config.opa_url}")
    private String OPA_SERVER_URL;

    /**
     * // TODO 客户端的搭建，注意优化性能，连接池，缓存等
     */
    private OpaQueryApi client;

    /**
     * 此前 OpaueryApi client = OpaClient.builder().opaConfiguration(OPA_SERVER_URL).build()
     * 会在OPA_SERVER_URL注入之前执行，导致获取到的OPA_SERVER_URL为空
     * 现在使用@PostConstruct延迟初始化，让OPA_SERVER_URL注入后再初始化client
     */
    @PostConstruct
    public void init() {
        if(OPA_SERVER_URL == null || OPA_SERVER_URL.isEmpty()) {
            throw new IllegalArgumentException("OPA_SERVER_URL 尚未初始化");
        }

        this.client = OpaClient.builder()
                .opaConfiguration(OPA_SERVER_URL)
                .build();
        log.info("OPA client 初始化成功");
    }

    /**
     * 根据输入和策略向OPA请求查询，并且封装成特定的输出
     * @param opaInput
     * @return
     */
    public OpaOutput querryForDocument(OpaInput opaInput) {
        QueryForDocumentRequest ageRequest = new QueryForDocumentRequest(opaInput, rules.RULES_PARUS);
        return client.queryForDocument(ageRequest, OpaOutput.class);
    }
}
